<template>
  <div class="ele-body">
    <!-- 数据表格 -->
    <el-card shadow="always" body-style="padding: 30px 40px">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="关键字：">
          <el-input
            style="width: 400px"
            v-model="formInline.title"
            placeholder="关键字"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button
            @click="handleOpen"
            style="margin-left: 30px"
            type="primary"
            >新增<i class="el-icon-plus el-icon--right"></i
          ></el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" width="100" label="序号">
        </el-table-column>
        <el-table-column prop="name" label="banner" width="320">
          <template slot-scope="scope">
            <el-image
              style="max-width: 100%; height: 100px"
              :src="scope.row.simgUrl"
              :preview-src-list="[scope.row.simgUrl]"
            >
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" width="280">
        </el-table-column>
        <el-table-column prop="content" label="内容" width="320">
        </el-table-column>
        <el-table-column prop="createDate" label="创建日期" width="200">
          <template slot-scope="scope">
            <p>{{ formatDateTime(scope.row.createDate) }}</p>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="200">
          <template slot-scope="scope">
            <el-button type="text" @click="onEdit(scope.row.id)" size="small"
              >编辑</el-button
            >
            <el-popconfirm
              @confirm="onConfirm(scope.row.id)"
              title="这是一段内容确定删除吗？"
            >
              <el-button
                style="margin-left: 20px; color: red"
                slot="reference"
                type="text"
                size="small"
                >删除</el-button
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="display: flex; justify-content: flex-end"
        background
        @current-change="handleCurrentChange"
        layout="total, prev, pager, next"
        :current-page.sync="currentPage"
        :total="totalNum"
        :page-size="10"
      >
      </el-pagination>
    </el-card>

    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      width="40%"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        ref="ruleForm"
        :rules="rules"
        label-position="right"
        label-width="90px"
        :model="form"
      >
        <el-form-item label="活动名称" prop="title">
          <el-input
            show-word-limit
            maxlength="30"
            style="width: 400px"
            v-model="form.title"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="Banner" prop="fileList">
          <el-upload
            :multiple="false"
            :limit="limit"
            :auto-upload="false"
            :file-list="form.fileList"
            action="#"
            list-type="picture-card"
            :on-change="handleChange"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            style="width: 400px"
            :rows="5"
            type="textarea"
            placeholder="请输入内容"
            v-model="form.content"
            maxlength="300"
            show-word-limit
          >
          </el-input>
        </el-form-item>
        <!-- <tinymce-editor v-model="form.content" :init="initDataEditor" /> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button
          v-if="title === '新增Banner'"
          type="primary"
          @click="addBanner"
          >确 定</el-button
        >
        <el-button
          v-if="title === '编辑Banner'"
          type="primary"
          @click="editBanner"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  GetBanner,
  DelBanner,
  GetGuid,
  AddBanner,
  UploadFile,
  GetBannerDetail,
  EditBanner
} from '@/api/basicdatamanager';
import TinymceEditor from '@/components/TinymceEditor'; // 富文本编辑器
export default {
  name: 'Banner',
  // components: { TinymceEditor },
  data() {
    return {
      itemDetail: {},
      title: '',
      limit: 1,
      guid: '',
      currentPage: 1,
      totalNum: 0,
      formInline: {
        title: ''
      },
      tableData: [],
      dialogFormVisible: false,
      form: {
        title: '',
        content: '',
        fileList: []
      },
      rules: {
        title: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        content: [
          { required: true, message: '请输入活动内容', trigger: 'blur' }
        ],
        fileList: [{ required: true, message: '请上传封面', trigger: 'change' }]
      },
      //富文本框初始数据
      initDataEditor: {
        height: 500,
        //去掉图片的宽、高
        image_dimensions: false,
        images_upload_handler: (blobInfo, success, failure) => {
          //上传力图片对像
          let fdata = new FormData();
          fdata.set('imgType', 51); //图片类型
          fdata.set('attType', 1); //文件类型
          fdata.set('orderIndex', 510); // 顺序
          fdata.set('file', blobInfo.blob());
          // fdata.set('businessId', this.form.id); // 业务ID
          fdata.set('fileName', blobInfo.blob().name); // 文件名称

          //上传图片
          UploadFile(fdata)
            .then((res) => {
              if (res != null && res != undefined) {
                success(res.fileAllPath);
              } else {
                failure(res.msg);
              }
            })
            .catch((e) => {
              this.$message.error(e.message);
            });
        }
      }
    };
  },
  created() {
    this.initData();
    this.getGuid();
  },
  methods: {
    formatDateTime(isoString) {
      const date = new Date(isoString);
      const year = date.getFullYear();
      const month = date.getMonth() + 1; // 月份从0开始，需+1
      const day = date.getDate();
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.initData();
    },
    handleChange(file, fileList) {
      this.$set(this.form, 'fileList', fileList);
      this.uploadImg();
    },
    // 上传图片
    uploadImg() {
      let fdata = new FormData();
      fdata.set('file', this.form.fileList[0].raw);
      fdata.set('imgType', 3); //图片类型
      fdata.set('attType', 1); //文件类型
      fdata.set('businessId', this.guid); // 业务ID
      //上传文件
      UploadFile(fdata)
        .then((res) => {
          console.log(this.form);
          this.$refs.ruleForm.validateField('fileList');
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    initData() {
      GetBanner({
        pageIndex: this.currentPage,
        pageSize: 10,
        conditions: {
          keyword: this.formInline.title,
          status: 0
        },
        orderBys: [
          {
            sort: 'createDate',
            order: 0
          }
        ]
      })
        .then((res) => {
          this.tableData = res.items;
          this.totalNum = res.totalrecords;
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    onEdit(id) {
      this.title = '编辑Banner';
      this.guid = id;
      this.getDetail(id);
      this.dialogFormVisible = true;
    },
    getDetail(id) {
      GetBannerDetail({
        id: id
      })
        .then((res) => {
          this.form = {
            title: res.title,
            content: res.content
          };
          this.itemDetail = res;
          this.form.fileList = [{ url: res.simgUrl }];
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    handleConfirm() {},
    editBanner() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          EditBanner({
            title: this.form.title,
            content: this.form.content,
            createDate: this.itemDetail.createDate,
            id: this.guid
          })
            .then((res) => {
              this.$message.success('修改成功');
              this.dialogFormVisible = false;
              this.initData();
            })
            .catch((e) => {
              this.$message.error(e.message);
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    addBanner() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          AddBanner({
            title: this.form.title,
            content: this.form.content,
            id: this.guid
          })
            .then((res) => {
              this.$message.success('新增成功');
              this.dialogFormVisible = false;
              this.initData();
            })
            .catch((e) => {
              this.$message.error(e.message);
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    delItem(id) {
      DelBanner({ id: id })
        .then((res) => {
          this.$message.success('删除成功');
          this.initData();
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    onConfirm(id) {
      this.delItem(id);
    },
    handleSearch() {
      this.currentPage = 1;
      this.initData();
    },
    handleReset() {
      this.formInline = {};
      this.currentPage = 1;
    },
    getGuid() {
      GetGuid()
        .then((res) => {
          this.guid = res;
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    handleOpen() {
      this.title = '新增Banner';
      this.form = {};
      this.getGuid();
      this.dialogFormVisible = true;
    }
  }
};
</script>
<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>